package com.crm.model.dto;


import com.alibaba.fastjson.JSONObject;
import com.crm.common.model.Enum.DictionaryEnum;
import com.crm.common.model.Enum.StatusCodeEnum;
import com.crm.common.util.CommonUtils;
import com.crm.model.entity.common.Dictionary;
import com.crm.model.entity.customerManager.Customer;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.vo.customerManager.CustomerImportNewVO;
import com.crm.service.common.DictionaryDbService;
import com.crm.service.customerManager.CustomerDbService;
import jdk.nashorn.internal.ir.Block;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.transaction.annotation.Transactional;

import java.beans.Transient;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;

/**
 * @ Author ：pym
 * @ Date   ：2021/5/17 11:22
 */
@Slf4j
public class InsertCustomerCallable implements Callable<JSONObject> {

    private CustomerDbService customerDbService;
    private DictionaryDbService dictionaryDbService;
    private String customerPoolId;
    private List<CustomerImportNewVO> list;
    private CountDownLatch begin;
    private CountDownLatch end;
    private Integer index;

    public InsertCustomerCallable(CustomerDbService customerDbService, DictionaryDbService dictionaryDbService,
                                  String customerPoolId, List<CustomerImportNewVO> list, CountDownLatch begin,
                                  CountDownLatch end,Integer index) {
        this.customerDbService = customerDbService;
        this.dictionaryDbService = dictionaryDbService;
        this.customerPoolId = customerPoolId;
        this.list = list;
        this.begin = begin;
        this.end = end;
        this.index = index;
    }

    @Override
    public JSONObject call() {
        //导入数量
        int importNum = 0;
        //重复的行数
        List<Integer> repeatIdStr = new ArrayList();
        //失败行数
        List<Integer> importFailIdStr = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            index = index +1;
            try {
                //客户名称
                String customerName = list.get(i).getCustomerName();
                //统一社会信用代码
                String unifiedSocialCreditCode = list.get(i).getUnifiedSocialCreditCode();
                Customer isCustomerRepeat = customerDbService.isCustomerRepeat(CommonUtils.removeCharacters(customerName), unifiedSocialCreditCode);
                if (isCustomerRepeat == null) {
                    Customer customer = getCustomer(list.get(i), customerPoolId,index);
                    Boolean insertResult = customerDbService.insertCustomer(customer);
                    if (insertResult) {
                        //导入成功
                        importNum = importNum + 1;
                    } else {
                        //导入失败
                        importFailIdStr.add(i+2);
                    }
                } else {
                    //客户重复
                    repeatIdStr.add(i+2);
                }
            } catch (Exception e) {
                //导入失败
                importFailIdStr.add(i+2);
                log.error("InsertCustomerCallable importCustomer error:", e);
            }
            end.countDown();
        }
        JSONObject result = new JSONObject();
        result.put("importNum",importNum);
        result.put("repeatIdStr",repeatIdStr);
        result.put("importFailIdStr",importFailIdStr);
        return result;
    }

    /**
     * 获取客户
     * @param customerImportVO - 客户参数
     * @param customerPoolId -客户池ID
     * @return
     */
    private Customer getCustomer(CustomerImportNewVO customerImportVO, String customerPoolId,Integer index) throws Exception {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        String accountId = userAccount.getAccountId();
        Customer customer = new Customer();
        customer.setCustomerId(CommonUtils.getGUID());
        customer.setCustomerName(CommonUtils.removeCharacters(customerImportVO.getCustomerName()));
        customer.setCustomerNumber(createCustomerNumber()+index);
        customer.setUnifiedSocialCreditCode(customerImportVO.getUnifiedSocialCreditCode());
        //customer.setOriginalCustomerId(customerImportVO.getOriginalCustomerId());
        //customer.setCustomerIndustryFirst(customerImportVO.getCustomerIndustryFirst());
        //customer.setCustomerIndustrySecond(customerImportVO.getCustomerIndustrySecond());
        //customer.setProvinceCode(customerImportVO.getProvinceCode());
        customer.setProvinceName(customerImportVO.getProvinceName());
        //customer.setCityCode(customerImportVO.getCityCode());
        customer.setCityName(customerImportVO.getCityName());
        //customer.setCountyCode(customerImportVO.getCountyCode());
        customer.setCountyName(customerImportVO.getCountyName());
        customer.setDetailedAddress(customerImportVO.getDetailedAddress());
        customer.setEnterpriseExternalPhone(customerImportVO.getEnterpriseExternalPhone());
        customer.setEnterpriseExternalLandline(customerImportVO.getEnterpriseExternalLandline());
        customer.setCompanyWebsite(customerImportVO.getCompanyWebsite());
        customer.setRegistrationNumber(customerImportVO.getRegistrationNumber());
        customer.setOrganizationCode(customerImportVO.getOrganizationCode());
        customer.setLegalRepresentative(customerImportVO.getLegalRepresentative());
        String registrationTime = customerImportVO.getRegistrationTime();
        if (isValidDate(registrationTime)) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期，比如2018-02-29会被接受，并转换成2018-03-01
            format.setLenient(false);
            customer.setRegistrationTime(format.parse(registrationTime));
        }
        customer.setInsuredNumber(isInteger(customerImportVO.getInsuredNumber()) ? Integer.parseInt(customerImportVO.getInsuredNumber()) : 0);
        //customer.setFax(customerImportVO.getFax());
        customer.setEmail(customerImportVO.getEmail());
        //customer.setRemark(customerImportVO.getRemark());
        customer.setCreatePeopleId(accountId);
        customer.setCreateTm(new Date());
        customer.setUpdatePeopleId(accountId);
        customer.setUpdateTm(new Date());
        customer.setAccountId(accountId);
        customer.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        //customer.setDealStatus(customerImportVO.getDealStatus());
        customer.setCustomerPoolId(customerPoolId);
        customer.setBusinessScope(customerImportVO.getBusinessScope());
        //customer.setTag(customerImportVO.getTag());

        //注册资本
        String registeredCapital = customerImportVO.getRegisteredCapital();
        if (!StringUtils.isBlank(registeredCapital)) {
            customer.setRegisteredCapital(CommonUtils.extractNumbers(registeredCapital));
        }
        //企业状态
        String enterpriseState = customerImportVO.getEnterpriseState();
        if (!StringUtils.isBlank(enterpriseState)) {
            Dictionary enterpriseStateDic = dictionaryDbService.selectDictionaryByDicName(DictionaryEnum.ENTERPRISE_STATE.getTypeCode(), enterpriseState);
            if (enterpriseStateDic != null) {
                customer.setEnterpriseState(enterpriseStateDic.getDictCode());
            } else {
                customer.setEnterpriseState("1");
            }
        }

        //资本类型
        /*String capitalType = customerImportVO.getCapitalType();
        if (!StringUtils.isBlank(capitalType)) {
            Dictionary capitalTypeDic = dictionaryDbService.selectDictionaryByDicName(DictionaryEnum.CAPITAL_TYPE.getTypeCode(), capitalType);
            if (capitalTypeDic != null) {
                customer.setCapitalType(capitalTypeDic.getDictCode());
            } else {
                customer.setCapitalType("3");
            }
        }*/

        //公司类型
        String companyType = customerImportVO.getCompanyType();
        if (!StringUtils.isBlank(companyType)) {
            Dictionary companyTypeDic = dictionaryDbService.selectDictionaryByDicName(DictionaryEnum.COMPANY_TYPE.getTypeCode(), companyType);
            if (companyTypeDic != null) {
                customer.setCompanyType(companyTypeDic.getDictCode());
            } else {
                customer.setCompanyType("22");
            }
        }

        //客户级别
        /*String customerLevel = customerImportVO.getCustomerLevel();
        if (!StringUtils.isBlank(customerLevel)) {
            Dictionary customerLevelDic = dictionaryDbService.selectDictionaryByDicName(DictionaryEnum.CLIENT_LEVEL.getTypeCode(), customerLevel);
            if (customerLevelDic != null) {
                customer.setCustomerLevel(customerLevelDic.getDictCode());
            }
        }*/

        //公司规模
       /* Integer companySize = customerImportVO.getCompanySize();
        if (companySize != null) {
            if (0 < companySize || companySize < 20) {
                customer.setCompanySize("1");
            } else if (20 <= companySize || companySize < 100) {
                customer.setCompanySize("2");
            } else if (100 <= companySize || companySize < 500) {
                customer.setCompanySize("3");
            } else if (500 <= companySize || companySize < 1000) {
                customer.setCompanySize("4");
            } else if (1000 <= companySize || companySize < 10000) {
                customer.setCompanySize("5");
            } else if (10000 < companySize) {
                customer.setCompanySize("6");
            }
        }*/

        //行业
        String industry = customerImportVO.getIndustry();
        if (!StringUtils.isBlank(industry)) {
            Dictionary industryDic = dictionaryDbService.selectDictionaryByDicName(DictionaryEnum.INDUSTRY.getTypeCode(), industry);
            if (industryDic != null) {
                customer.setIndustry(industryDic.getDictCode());
            } else {
                customer.setIndustry("21");
            }
        }
        //客户来源
        /*String customerSource = customerImportVO.getCustomerSource();
        if (!StringUtils.isBlank(customerSource)) {
            Dictionary customerSourceDic = dictionaryDbService.selectDictionaryByDicName(DictionaryEnum.CUSTOMER_SOURCE.getTypeCode(), customerSource);
            if (customerSourceDic != null) {
                customer.setCustomerSource(customerSourceDic.getDictCode());
            } else {
                //来源设置其他
                customer.setCustomerSource("11");
            }
        }*/

        //客户状态
        /*String customerState = customerImportVO.getCustomerState();
        if (!StringUtils.isBlank(customerState)) {
            Dictionary customerStateDic = dictionaryDbService.selectDictionaryByDicName(DictionaryEnum.CUSTOMER_STATE.getTypeCode(), customerState);
            if (customerStateDic != null) {
                customer.setCustomerState(customerStateDic.getDictCode());
            }
        }*/
        //客户类型
        customer.setCustomerType("0");//企业客户
        //目前状态
        customer.setPotentialCustomers(0);//无意向客户

        //客户类型
       /* String customerType = customerImportVO.getCustomerType();
        if (!StringUtils.isBlank(customerType)) {
            Dictionary customerTypeDic = dictionaryDbService.selectDictionaryByDicName(DictionaryEnum.CUSTOMER_TYPE.getTypeCode(), customerType);
            if (customerTypeDic != null) {
                customer.setCustomerType(customerTypeDic.getDictCode());
            }
        }*/

        //目前状态
        customer.setCurrentStatus(Short.parseShort("0"));//未领取
        return customer;
    }

    /**
     * 判断是否为整数
     * @param str
     * @return
     */
    private boolean isInteger(String str) {
        return StringUtils.isNotBlank(str) ? str.matches("^[0-9]*$") : false;
    }

    /**
     * 判断一个字符串是否为合法日期
     * @Author pym
     * @Date  2021/4/28 16:33
     * @param strDate -字符串
     * @return {@link {boolean}}
     */
    public boolean isValidDate(String strDate) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期，比如2018-02-29会被接受，并转换成2018-03-01
            format.setLenient(false);
            Date date = format.parse(strDate);

            //判断传入的yyyy年-MM月-dd日 字符串是否为数字
            String[] sArray = strDate.split("-");
            for (String s : sArray) {
                boolean isNum = s.matches("[0-9]+");
                //+表示1个或多个（如"3"或"225"），*表示0个或多个（[0-9]*）（如""或"1"或"22"），?表示0个或1个([0-9]?)(如""或"7")
                if (!isNum) {
                    return false;
                }
            }
        } catch (Exception e) {
            // e.printStackTrace();
            // 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
            return false;
        }
        return true;
    }

    /**
     * 生成客户编号
     * @return
     */
    public String createCustomerNumber(){
        String datetime = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String newCustomerNumber =datetime+"00001";
        String maxCustomerNumber = customerDbService.selectMaxCustomerNumber(datetime);
        if (Objects.nonNull(maxCustomerNumber)){
            maxCustomerNumber = maxCustomerNumber.substring(0,13);
            if (maxCustomerNumber.length() < 8){
                maxCustomerNumber = customerDbService.selectMaxCustomerNumber(datetime);
                if (Objects.isNull(maxCustomerNumber)){
                    return newCustomerNumber;
                }
            }
            if (datetime.equals(maxCustomerNumber.substring(0,8))){
                newCustomerNumber =datetime+String.format("%05d",Integer.parseInt(maxCustomerNumber.substring(8))+1);
            }
        }
        return newCustomerNumber;
    }

}
